package com.filetransfer.app.ui.upload;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;

import java.io.IOException;
import java.io.InputStream;
public class FileHelper {
    public static String getFileNameFromUri(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex >= 0) {
                        result = cursor.getString(nameIndex);
                    }
                }
            }
        }
        if (result == null) {
            result = uri.getLastPathSegment();
        }
        return result;
    }
    public static InputStream getFileInputStreamForUri(Context context, Uri uri) throws IOException {
        ContentResolver contentResolver = context.getContentResolver();
        return contentResolver.openInputStream(uri);
    }
    //    private File getFile(Context context, Uri uri) {
    //        String filePath = null;
    //        if (uri.getScheme().equals("file")) {
    //            filePath = uri.getPath();
    //        } else if (uri.getScheme().equals("content")) {
    //            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
    //                if (cursor != null && cursor.moveToFirst()) {
    //                    int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    //                    if (index >= 0) {
    //                        filePath = cursor.getString(index);
    //                    }
    //                }
    //            }
    //        }
    //        if (filePath == null) {
    //            filePath = uri.getLastPathSegment();
    //        }
    //        return new File(filePath);
    //    }
    //    public void saveFileFromInputStream(InputStream inputStream, File targetFile) throws IOException {
    //        try (FileOutputStream outputStream = new FileOutputStream(targetFile)) {
    //            byte[] buffer = new byte[1024 * 1024];  // 1MB 每次读取
    //            int bytesRead;
    //            while ((bytesRead = inputStream.read(buffer)) != -1) {
    //                outputStream.write(buffer, 0, bytesRead);
    //            }
    //        }
    //    }
}
